package com.xlhj.upload.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.StringJoiner;
import java.util.UUID;

/**
 * @ClassName FileUploadController
 * @Description 文件上传控制器
 * @Author liucaijing
 * @Date 2021/2/23 13:44
 * @Version 1.0
 */
@RestController
public class FileUploadController {

    /**
     * 上传单个文件
     * @param uploadFile
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
        String format = LocalDate.now().format(dtf);
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/uploadFile/" + format + newName;
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }

    /**
     * 批量上传文件
     * @param uploadFiles
     * @param request
     * @return
     */
    @PostMapping("/uploads")
    public String uploads(MultipartFile[] uploadFiles, HttpServletRequest request) {
        String filePaths = "";
        StringJoiner stringJoiner = new StringJoiner("&&");
        try {
            if (uploadFiles.length > 0) {
                for (MultipartFile file : uploadFiles) {
                    String filePath = upload(file, request);
                    stringJoiner.add(filePath);
                }
            }
            filePaths = stringJoiner.toString();
            return filePaths;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }
}
